#include <iostream>
#include "sockdist.h"
#include "sock.h"
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include<string>
#include "stdio.h"
#include <cstdlib>
//#include <sys/socket.h> 

using namespace std;

#include "ClientUDP.h"


ClientUDP::ClientUDP(){
}

ClientUDP::ClientUDP(string h,int p,int t):Hote(p,t){

// Demande de BR local
  Sock brcli(SOCK_DGRAM,0);
  
  // On recupere le descripteur
  if(brcli.good()) {
    Hote::descBrLocale=brcli.getsDesc();
    cout << "# Demande de BR locale : OK" << endl;
  }
  
  else{
    cout << "Probleme BR Local" << endl;
    exit(1);
  }
  

  // Designation de la BR distante.
  hostnameDistant = h;
  SockDist brPub(Hote::conversionStringChar(hostnameDistant),(short)Hote::port);
  adrBrDistante = brPub.getAdrDist();
  lgBrDistante = brPub.getsLen();

 bool bOptVal = true;
  int bOptLen = sizeof(bool);
  if((int)setsockopt(descBrLocale,SOL_SOCKET, SO_BROADCAST, (char*)&bOptVal, lgBrDistante) !=  -1){  
    printf("Set SO_BROADCAST: ON\n");
  }
}

void ClientUDP::envoyer(string t){
//envoie
 tamponSnd = conversionStringChar(t);

 int retourSend = sendto(Hote::descBrLocale,tamponSnd,Hote::tailleTampon,0,(sockaddr*)adrBrDistante,(socklen_t)lgBrDistante);
  
  if (retourSend == -1){
    perror("# sendTo");
    exit(EXIT_FAILURE);
  }
 else {
    cout<<"# message envoye"<<endl;
  }
}
  

string ClientUDP::recevoir(){
  
  int retourRecv = recvfrom(Hote::descBrLocale,tamponRcv,Hote::tailleTampon,0,(sockaddr*)adrBrDistante,&lgBrDistante);
  if (retourRecv== -1){
    perror("# recvfrom ");
    exit(EXIT_FAILURE);
  }
  
  else{
    return conversionCharString(tamponRcv);
  }
  
}
